import {uSelectDevFunBydDevId, uSelectMyDevManagerData} from '@/api/deviceManagement'
import {UtilButtonLine} from '@/components/btn/utilBtn'
import {CCard} from '@/components/card'
import {DeviceStatusOfStatus, IconImg, ParamOfIcon} from '@/components/image'
import {DeviceConfigByCard} from '@/components/others/deviceConfig'
import RollerDigital from '@/components/rollerDigital'
import {SplitLine} from '@/components/splitLine'
import {CnBoldP, CnBoldSpan, CnMediumP, CnMediumSpan, CnNormalSpan} from '@/components/text'
import WaterTarget from '@/components/waterTarget'
import useLoading from '@/hooks/loading'
import {getUserId} from '@/libs/auth'
import {toDevInfo} from '@/libs/pageRedirect'
import {ratio2color} from '@/libs/text2Color'
import {state} from '@/store/login'
import {PropType} from 'vue'

const ConfigInofItem = defineComponent({
  props: {
    btnText: String,
    title: String
  },
  setup(props, ctx) {
    return () => (
      <div class='h-30 flex justify-between items-center'>
        <div>
          <IconImg imgName='standard-sm' class='inline-block mr-10 w-18 h-18'></IconImg>
          <CnNormalSpan class='text-12'>{props.title || ''}</CnNormalSpan>
        </div>
        <CnNormalSpan class='text-primaryHalf cursor-pointer text-12'>
          {props.btnText || ''}
        </CnNormalSpan>
      </div>
    )
  }
})

onMounted(() => {})
const goToDevInfo = (devInfo: object, devList: []) => {
  // console.log(state)
  console.log(devList)
  console.log(devInfo)

  devList.forEach(item => {
    if (item.devId == devInfo.devInfo.devId) {
      devInfo.devInfo.devGId = item.devGId
    }
  })

  // console.log(devInfo)
  toDevInfo(devInfo)
}

export const DeviceCard = defineComponent({
  props: {
    dev: {
      type: Object as PropType<SimpleDeviceData>,
      required: true
    },
    currentDevId: Number,
    devListData: []
  },
  emits: {
    finish: (): boolean => true,
    actived: (currentDev: SimpleDeviceData): boolean => true
  },
  setup(props, {emit}) {
    const {loading, startLoading, closeLoading} = useLoading()

    const state = reactive<{
      shareModalVisible: boolean
      checkShareModelVisible: boolean
      utils: DeviceManagement.UtilData[]
      cardType: 'info' | 'utils'
      devBaseInfo: DeviceManagement.DevInfo | undefined
    }>({
      shareModalVisible: false,
      checkShareModelVisible: false,
      utils: [],
      cardType: 'info',
      devBaseInfo: undefined
    })

    const shareUserJoin = computed(() => state.devBaseInfo?.shareUserPack.shareNameList.join(','))

    watch(
      () => props.dev,
      n => {
        getDevBaseInfo()
      },
      {immediate: true}
    )

    function getUtils() {
      startLoading()
      uSelectDevFunBydDevId({devId: props.dev.devId})
        .then(res => {
          console.log(res)
          state.utils = res.data
          closeLoading()
        })
        .catch(err => {
          state.utils = []
          closeLoading()
        })
    }

    function getDevBaseInfo() {
      const userId = getUserId()
      if (!userId) return
      startLoading()
      uSelectMyDevManagerData({userId, devId: props.dev.devId})
        .then(res => {
          console.log(res)
          state.devBaseInfo = res.data
          closeLoading()
        })
        .catch(err => {
          state.devBaseInfo = undefined
          closeLoading()
        })
    }

    return () => (
      <CCard
        class='h-456 col-span-1 rounded-4 bg-white overflow-hidden flex flex-col px-0'
        title={props.dev.devName || '设备名称为空'}
        v-slots={{
          title: () => (
            <div class='w-full h-full flex justify-between items-center px-20'>
              <CnBoldSpan>{props.dev.devName || '设备名称为空'}</CnBoldSpan>
              <DeviceStatusOfStatus status={props.dev.devStatusCode}>
                <CnBoldSpan class='text-16'>{props.dev.devStatus || '无状态'}</CnBoldSpan>
              </DeviceStatusOfStatus>
            </div>
          )
        }}
        actived={
          (props.currentDevId ?? undefined) !== undefined && props.currentDevId === props.dev.devId
        }
        onClick={e => {
          e.preventDefault()
          emit('actived', props.dev)
        }}
        loading={loading.value}
      >
        {state.cardType === 'info' ? (
          state.devBaseInfo ? (
            <div class='w-full flex-1 overflow-y-auto mb-42 px-20 flex flex-col '>
              {/* 水质分析 */}
              <div class='w-full min-h-64 flex items-center mt-16'>
                <WaterTarget
                  id={'deviceTarget' + (state.devBaseInfo?.devId || Math.random())}
                  radius={20}
                  range={((state.devBaseInfo?.nowStandRatio || 0) / 100) * 360}
                  borderColor={ratio2color(state.devBaseInfo?.nowStandRatio || 0)}
                  showDashed={false}
                  borderWidth={2}
                >
                  <RollerDigital
                    class='text-15'
                    style={{
                      color: ratio2color(state.devBaseInfo?.nowStandRatio || 0)
                    }}
                    endVal={state.devBaseInfo?.nowStandRatio}
                    bold={false}
                  ></RollerDigital>
                </WaterTarget>
                <div class='flex-1 ml-24 overflow-x-hidden flex flex-col'>
                  <CnBoldP>{state.devBaseInfo?.checkResult || '无参数状态'}</CnBoldP>
                  <div class='flex flex-wrap leading-24'>
                    {state.devBaseInfo?.paramList.map((param, idx, arr) => (
                      <ParamOfIcon
                        class={`text-left flex justify-center ${
                          idx !== arr.length - 1 ? 'mr-16' : ''
                        }`}
                        imgName={param.paramName}
                        imgStyle={{
                          width: '16px',
                          height: '16px'
                        }}
                      >
                        {param.paramName}
                      </ParamOfIcon>
                    ))}
                  </div>
                </div>
              </div>

              {/* 配置信息 */}
              <DeviceConfigByCard devData={state.devBaseInfo}></DeviceConfigByCard>
              {/* <div class='w-full'>
                <div class='h-64 flex items-center'>
                  <WaterTarget
                    id={'deviceConfigInfo-' + (state.devBaseInfo?.devId || Math.random())}
                    radius={20}
                    borderWidth={2}
                    range={((state.devBaseInfo?.onlineTimeRatio || 0) / 100) * 360}
                    borderColor={ratio2color(state.devBaseInfo?.onlineTimeRatio || 0)}
                    showDashed={false}
                  >
                    <RollerDigital
                      class='text-15'
                      endVal={state.devBaseInfo?.onlineTimeRatio}
                      style={{
                        color: ratio2color(state.devBaseInfo?.onlineTimeRatio || 0)
                      }}
                      bold={false}
                    ></RollerDigital>
                  </WaterTarget>
                  <CnBoldSpan class='ml-24'>{state.devBaseInfo?.devOnlineStatus || ''}</CnBoldSpan>
                </div>
                <div class='pl-66'>
                  <ConfigInofItem
                    title={`标准设置` + (state.devBaseInfo?.standSetStatus || '未配置')}
                    btnText='设置标准'
                  ></ConfigInofItem>
                  <ConfigInofItem
                    title={`数据采集` + (state.devBaseInfo?.dataSetStatus || '未配置')}
                    btnText='设置采集'
                  ></ConfigInofItem>
                  <ConfigInofItem
                    title={`报警设置` + (state.devBaseInfo?.standSetStatus || '未配置')}
                    btnText='设置报警'
                  ></ConfigInofItem>
                </div>
              </div> */}

              {/* 底部信息 包含异常信息 分享信息 位置信息 */}
              <div class='w-full mt-20'>
                <div class='h-20 flex justify-end items-center mb-12'>
                  <CnNormalSpan class='h-full text-12 mr-10'>
                    本周报警
                    {/* <CnNormalSpan class='h-full text-warning mx-6'>{state.devBaseInfo?.totalExceptionCount}</CnNormalSpan> */}
                    <RollerDigital
                      class='h-full text-14 text-warning mx-6'
                      endVal={state.devBaseInfo?.totalExceptionCount || 0}
                      bold={false}
                    ></RollerDigital>
                    次
                  </CnNormalSpan>
                  <div class='inline-block w-1 h-full bg-splitLine'></div>
                  <CnNormalSpan class='h-full text-12 mx-10'>
                    设备故障
                    {/* <CnNormalSpan class='h-full text-warning mx-6'>{state.devBaseInfo?.devExceptionCount || 0}</CnNormalSpan> */}
                    <RollerDigital
                      class='h-full text-14 text-warning mx-6'
                      endVal={state.devBaseInfo?.devExceptionCount || 0}
                      bold={false}
                    ></RollerDigital>
                    次
                  </CnNormalSpan>
                  <div class='inline-block w-1 h-full bg-splitLine'></div>
                  <CnNormalSpan class='h-full text-12 ml-10'>
                    水质异常
                    {/* <CnNormalSpan class='h-full text-warning mx-6'>{state.devBaseInfo?.paramExceptionCount || 0}</CnNormalSpan> */}
                    <RollerDigital
                      class='h-full text-14 text-warning mx-6'
                      endVal={state.devBaseInfo?.paramExceptionCount || 0}
                      bold={false}
                    ></RollerDigital>
                    次
                  </CnNormalSpan>
                </div>
                <div class='w-full h-18 flex items-center justify-end mb-8 space-x-16'>
                  <CnNormalSpan class='inline-block w-71 text-12'>
                    已分享
                    <CnNormalSpan class='text-text mx-4'>
                      {state.devBaseInfo?.shareUserPack.shareCount || 0}
                    </CnNormalSpan>
                    人
                  </CnNormalSpan>
                  <a-tooltip placement='top' title={shareUserJoin.value}>
                    <CnNormalSpan
                      class='text-12'
                      style={{
                        maxWidth: 'calc(100% - 87px)'
                      }}
                    >
                      {shareUserJoin.value}
                    </CnNormalSpan>
                  </a-tooltip>
                </div>
                <div class='h-18 flex items-center justify-end space-x-16 mb-0 '>
                  <CnNormalSpan class='text-12'>
                    {state.devBaseInfo?.address || '无地址'}
                  </CnNormalSpan>
                  <CnBoldSpan class='text-12'>
                    {state.devBaseInfo?.beLongUser || '无所属人'}
                  </CnBoldSpan>
                </div>
              </div>
            </div>
          ) : (
            <div class='flex items-center justify-center'>
              <a-spin loading={true}></a-spin>
            </div>
          )
        ) : state.cardType === 'utils' ? (
          <div
            class={`grid grid-cols-3 gapx-x-69 gap-y-28 place-items-center place-content-center mt-56 p-20`}
          >
            {state.utils.map((item, idx, arr) => (
              <UtilButtonLine value={item}></UtilButtonLine>
            ))}
          </div>
        ) : null}

        {/* <div class={`flex ${state.utils.length <= 1 ? 'justify-start' : 'justify-around'} items-center flex-wrap gap-y-20 p-20`}> */}

        <div
          class='absolute bottom-0 left-0 w-full h-52 px-50 flex justify-between items-center'
          style={{
            background: '#E4EAF5'
          }}
        >
          {state.cardType === 'info' ? (
            [
              <div
                class='flex justify-start items-center flex-1 cursor-pointer'
                onClick={e => {
                  e.stopPropagation()
                  e.preventDefault()
                  state.devBaseInfo && goToDevInfo({devInfo: state.devBaseInfo}, props.devListData)
                }}
              >
                <IconImg imgName='edit-content' class='w-24 h-24 mr-12'></IconImg>
                <CnMediumSpan class='text-xText'>修改设备信息</CnMediumSpan>
              </div>,
              <SplitLine class='py-14'></SplitLine>,
              <div
                class='flex justify-end items-center flex-1 cursor-pointer'
                onClick={e => {
                  e.stopPropagation()
                  e.preventDefault()
                  state.cardType = 'utils'
                  getUtils()
                }}
              >
                <IconImg imgName='more' class='w-24 h-24 mr-12'></IconImg>
                <CnMediumSpan class='text-xText'>更多功能</CnMediumSpan>
              </div>
            ]
          ) : (
            <CnMediumP
              class='flex-1 w-full flex justify-end items-center  cursor-pointer'
              onClick={e => {
                e.stopPropagation()
                e.preventDefault()
                state.cardType = 'info'
              }}
            >
              返回
            </CnMediumP>
          )}
        </div>
      </CCard>
    )
  }
})
